<template>
	<a-card title="上传房源" :body-style="{ padding: '24px' }">
		<a-form ref="houseForm" :model="form" :rules="rules" layout="vertical">
			<!-- 第一行：房源标题、小区、楼层 -->
			<a-row :gutter="24">
				<a-col :span="8">
					<a-form-item label="房源标题" name="title">
						<a-input v-model:value="form.title" placeholder="请输入房源标题" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="小区名称(非必填)">
						<a-input v-model:value="form.community" placeholder="请输入小区名称" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="楼层" name="floor">
						<a-input-number v-model:value="form.floor" placeholder="请输入楼层" style="width: 100%" />
					</a-form-item>
				</a-col>
			</a-row>

			<!-- 第二行：地区、详细地址、地图按钮 -->
			<a-row :gutter="24">
				<a-col :span="8">
					<a-form-item label="地区" required>
						<a-input v-model:value="form.region" disabled />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="详细地址" name="address">
						<a-input v-model:value="form.address" placeholder="请输入详细地址" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="房源定位" required>
						<a-button class="ml-4" block :disabled="!form.address" @click="openMapPicker"> 打开地图确定位置 </a-button>
						<!-- 地图选择弹窗 -->
						<a-modal
							v-model:open="visible"
							:destroyOnClose="false"
							title="选择位置"
							:confirmLoading="confirmLoading"
							@ok="onConfirm"
							cancelText="取消"
							okText="确认位置"
							width="40vw"
						>
							<div ref="mapRef" class="map-container"></div>
						</a-modal>
					</a-form-item>
				</a-col>
			</a-row>

			<!-- 第三行：房源描述 -->
			<a-row :gutter="24">
				<a-col :span="24">
					<a-form-item label="房源描述" name="description">
						<a-textarea v-model:value="form.description" placeholder="请输入房源描述" :rows="2" />
					</a-form-item>
				</a-col>
			</a-row>

			<!-- 第四行：房型 -->
			<a-row :gutter="24">
				<a-col :span="24">
					<a-form-item label="房型（例如1房1厅1卫）" name="houseType">
						<a-row :gutter="8">
							<a-col :span="8">
								<a-select v-model:value="room" placeholder="请选择房间数量">
									<a-select-option value="1">1房</a-select-option>
									<a-select-option value="2">2房</a-select-option>
									<a-select-option value="3">3房</a-select-option>
								</a-select>
							</a-col>
							<a-col :span="8">
								<a-select v-model:value="hall" placeholder="请选择客厅数量">
									<a-select-option value="0">0厅</a-select-option>
									<a-select-option value="1">1厅</a-select-option>
									<a-select-option value="2">2厅</a-select-option>
									<a-select-option value="3">3厅</a-select-option>
								</a-select>
							</a-col>
							<a-col :span="8">
								<a-select v-model:value="bathroom" placeholder="请选择卫生间数量">
									<a-select-option value="1">1卫</a-select-option>
									<a-select-option value="2">2卫</a-select-option>
									<a-select-option value="3">3卫</a-select-option>
								</a-select>
							</a-col>
						</a-row>
					</a-form-item>
				</a-col>
			</a-row>
			<!-- 租金、租期、支付方式 -->
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="面积" name="area">
						<a-input-number v-model:value="form.area" placeholder="请输入面积" style="width: 100%" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="租金" name="price">
						<a-input-number v-model:value="form.price" placeholder="请输入租金" style="width: 100%" />
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="租期" name="lease">
						<a-select v-model:value="form.lease" placeholder="请选择租期" style="width: 100%">
							<a-select-option value="一个月起">一个月起</a-select-option>
							<a-select-option value="三个月起">三个月起</a-select-option>
							<a-select-option value="半年起">半年起</a-select-option>
							<a-select-option value="一年起">一年起</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="支付方式" name="payType">
						<a-input v-model:value="form.payType" placeholder="例如：押一付一" />
					</a-form-item>
				</a-col>
			</a-row>
			<!-- 配套设施、所属商圈、附近地铁站 、步行时间 -->
			<a-row :gutter="24">
				<a-col :span="6">
					<a-form-item label="配套设施（多选）" name="facilities">
						<a-select
							mode="multiple"
							v-model:value="facilitiesSelected"
							placeholder="请选择配套设施"
							@change="handleFacilitiesChange"
						>
							<a-select-option v-for="item in facilitiesOptions" :key="item" :value="item">
								{{ item }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="所属商圈" name="businessArea">
						<a-select v-model:value="form.businessArea" placeholder="请选择商圈">
							<a-select-option v-for="area in businessAreas" :key="area" :value="area">
								{{ area }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="附近地铁站" name="subwayStation">
						<a-select v-model:value="form.subwayStation" placeholder="请选择地铁站">
							<a-select-option v-for="station in subwayStations" :key="station" :value="station">
								{{ station }}
							</a-select-option>
						</a-select>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-form-item label="步行到地铁站时间（分钟）" name="traffic">
						<a-input-number v-model:value="form.traffic" placeholder="请输入步行时间" style="width: 100%" />
					</a-form-item>
				</a-col>
			</a-row>

			<!-- 第七行：图片上传 -->
			<a-row :gutter="24">
				<a-col :span="24">
					<a-form-item label="房源图片" name="imageUrls">
						<a-upload
							:fileList="fileList"
							:beforeUpload="beforeUpload"
							:onRemove="handleRemove"
							list-type="picture-card"
							multiple
							:isImageUrl="() => true"
							:maxCount="5"
						>
							<div>
								<PlusOutlined />
								<div style="margin-top: 8px">选择图片</div>
							</div>
						</a-upload>
					</a-form-item>
				</a-col>
			</a-row>
			<!-- 在图片上传模块后新增产权证明模块 -->
			<a-row :gutter="24">
				<a-col :span="24">
					<a-form-item label="产权证明（仅支持PDF文件）" name="titleDeed">
						<a-upload
							:beforeUpload="beforeUploadTitleDeed"
							:onRemove="handleRemoveTitleDeed"
							list-type="text"
							:maxCount="1"
							:accept="'.pdf'"
						>
							<a-button>
								<UploadOutlined />
								上传产权证明
							</a-button>
							<a-button type="primary" v-if="form.titleDeed" @click="previewTitleDeed" style="margin-left: 20px"
								>预览
							</a-button>
						</a-upload>
					</a-form-item>
				</a-col>
			</a-row>
			<!-- 第八行：提交按钮 -->
			<a-row :gutter="24">
				<a-col :span="24">
					<a-form-item>
						<a-button type="primary" @click="submitHouse" block>上传房源</a-button>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
</template>

<script setup>
	import { ref, watch, nextTick, reactive } from 'vue';
	import { message, Modal } from 'ant-design-vue';
	import landlordApi from '@/api/landlordApi';
	import AMapLoader from '@amap/amap-jsapi-loader';
	import { PlusOutlined } from '@ant-design/icons-vue';

	const houseForm = ref(null);
	const subwayStations = ref([
		'高增',
		'清塘',
		'清布',
		'莲塘',
		'马鞍山公园',
		'花都广场',
		'花果山公园',
		'花城路',
		'广州北站',
		'花都汽车城',
		'飞鹅岭'
	]);

	const businessAreas = [
		'花都广场/区政府',
		'来又来/大润发',
		'白云国际机场',
		'新世纪广场',
		'花山',
		'狮岭',
		'雅瑶',
		'融创茂',
		'雅房乐锦城/保利花城',
		'骏壹万邦',
		'建设北路'
	];

	const form = ref({
		title: '',
		description: '',
		community: '',
		region: '广东省广州市花都区',
		address: '',
		houseType: '',
		facilities: '',
		price: '',
		area: '',
		floor: '',
		businessArea: null,
		subwayStation: null,
		lease: null,
		payType: '',
		traffic: '',
		longitude: '',
		latitude: '',
		imageUrls: [],
		titleDeed: '', // 新增产权证明URL字段
		fileType: '' // 新增产权证明文件类型
	});

	const fileList = ref([]);
	const facilitiesSelected = ref([]);
	const facilitiesOptions = ['床', '厨房', '热水器', '空调', '网络', '电视', '冰箱', '洗衣机', '衣柜', '电梯'];

	// 房型相关字段
	const room = ref(null);
	const hall = ref(null);
	const bathroom = ref(null);
	watch([room, hall, bathroom], ([r, h, b]) => {
		if (r && h && b) {
			form.value.houseType = `${r}房${h}厅${b}卫`;
		} else {
			form.value.houseType = '';
		}
	});

	const rules = ref({
		title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
		description: [{ required: true, message: '房源描述不能为空', trigger: 'blur' }],
		community: [{ required: true, message: '小区不能为空', trigger: 'blur' }],
		address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
		houseType: [{ required: true, message: '房型不能为空', trigger: 'blur' }],
		facilities: [{ required: true, message: '请选择配套设施', trigger: 'change' }],
		price: [{ required: true, message: '租金不能为空', trigger: 'blur' }],
		area: [{ required: true, message: '面积不能为空', trigger: 'blur' }],
		floor: [{ required: true, message: '楼层不能为空', trigger: 'blur' }],
		businessArea: [{ required: true, message: '商圈不能为空', trigger: 'blur' }],
		subwayStation: [{ required: true, message: '地铁站不能为空', trigger: 'blur' }],
		lease: [{ required: true, message: '租期不能为空', trigger: 'blur' }],
		payType: [{ required: true, message: '支付方式不能为空', trigger: 'blur' }],
		traffic: [{ required: true, message: '请输入步行到地铁站的时间', trigger: 'blur' }],
		longitude: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
		latitude: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
		imageUrls: [{ required: true, message: '请上传房源图片', trigger: 'blur' }],
		titleDeed: [{ required: true, message: '请上传产权证明', trigger: 'blur' }]
	});

	// 图片上传，使用 .then 的方式
	const beforeUpload = (file) => {
		const formData = new FormData();
		formData.append('file', file);
		landlordApi
			.uploadHouseImg(formData)
			.then((response) => {
				if (response.code === 200) {
					// 因为返回的是数组，取第 0 个元素作为图片 URL
					const imageUrl = response.data[0];
					// 确保是一个字符串链接
					form.value.imageUrls.push(imageUrl);

					fileList.value.push({
						uid: file.uid,
						name: file.name,
						status: 'done',
						url: imageUrl
					});
					message.success('图片上传成功');
				} else {
					message.error(response.message || '图片上传失败');
				}
			})
			.catch((error) => {
				message.error('图片上传失败，请重试');
			});
		return false; // 阻止默认上传行为
	};

	const handleRemove = (file) => {
		fileList.value = fileList.value.filter((f) => f.uid !== file.uid);
		form.value.imageUrls = form.value.imageUrls.filter((url) => url !== file.url);
	};

	const handleFacilitiesChange = (value) => {
		facilitiesSelected.value = value;
		form.value.facilities = value.join(',');
	};

	const submitHouse = () => {
		if (!houseForm.value) return;
		houseForm.value
			.validate()
			.then(() => {
				//如果经纬度没有值
				if (!form.value.longitude || !form.value.latitude) {
					message.error('请点击地图选择器按钮确认位置');
					return;
				}

				Modal.confirm({
					title: '确认提交房源信息吗？',
					okText: '确认',
					cancelText: '取消',
					onOk() {
						landlordApi
							.uploadHouse(form.value)
							.then((res) => {
								if (res.code === 200) {
									message.success('房源上传成功');
									resetForm();
								} else {
									message.error(res.message || '房源上传失败');
								}
							})
							.catch((err) => {
								message.error('房源上传失败，请重试');
							});
					}
				});
			})
			.catch((err) => {
				console.error(err);
				message.error('请检查表单信息是否填写完整或正确');
			});
	};

	const resetForm = () => {
		Object.assign(form.value, {
			title: '',
			description: '',
			community: '',
			address: '',
			houseType: '',
			facilities: '',
			price: '',
			area: '',
			floor: '',
			businessArea: '',
			subwayStation: '',
			lease: '',
			payType: '',
			traffic: '',
			longitude: '',
			latitude: '',
			imageUrls: [],
			region: '广东省广州市花都区',
			titleDeed: '', // 新增产权证明URL字段
			fileType: '' // 新增产权证明文件类型
		});
		// 重置独立的房型变量
		room.value = null;
		hall.value = null;
		bathroom.value = null;

		fileList.value = [];
		facilitiesSelected.value = [];
		if (houseForm.value) {
			houseForm.value.resetFields();
		}
	};

	// 将 region 和 address 拼接为完整地址
	const getFullAddress = () => {
		return form.value.region + form.value.address;
	};

	const AMAP_KEY = import.meta.env.VITE_AMAP_KEY;
	const SECURITY_KEY = import.meta.env.VITE_SECURITY_KEY;
	const visible = ref(false);
	const mapRef = ref(null);
	const mapIns = ref(null);
	const result = reactive({
		location: '',
		address: '',
		lngAndLat: ''
	});

	const openMapPicker = () => {
		visible.value = true;
		nextTick(() => {
			const fullAddress = getFullAddress();
			if (mapIns.value) {
				updateMapCenter(fullAddress);
			} else {
				renderMap(fullAddress);
			}
		});
	};

	const updateMapCenter = async (address) => {
		const AMap = await loadAMap();
		const geocoder = new AMap.Geocoder({
			city: '020', // 可选：设置城市，限制范围
			radius: 500 // 搜索范围
		});

		geocoder.getLocation(address, (status, result) => {
			if (status === 'complete' && result.geocodes.length) {
				const { lng, lat } = result.geocodes[0].location;

				if (mapIns.value) {
					// 更新地图中心点
					mapIns.value.setCenter([lng, lat]);
					console.log(`地图中心点的地址为：` + address + `，经纬度 ${lng},${lat}`);

					// 更新标记位置
					if (mapMarker.value) {
						mapMarker.value.setPosition([lng, lat]);
					} else {
						// 如果标记不存在，则新建一个标记
						mapMarker.value = new AMap.Marker({
							position: [lng, lat],
							map: mapIns.value
						});
					}

					// 更新表单数据中的经纬度
					form.value.latitude = lat;
					form.value.longitude = lng;
				}
			} else {
				console.error('地址解析失败:', address);
			}
		});
	};

	watch(
		() => form.value.address,
		(newAddress) => {
			const fullAddress = getFullAddress();
			renderMap(fullAddress);
		}
	);

	window._AMapSecurityConfig = {
		securityJsCode: import.meta.env.VITE_SECURITY_JSCODE
	};

	const mapMarker = ref(null);
	const loadAMap = () => {
		return AMapLoader.load({
			key: AMAP_KEY,
			version: '2.0',
			securityJsCode: SECURITY_KEY,
			plugins: ['AMap.Geocoder', 'AMap.Marker']
		}).catch((error) => {
			console.error('AMap 加载失败', error);
			return null;
		});
	};

	const renderMap = (address) => {
		console.log('---------------------------------');
		AMapLoader.load({
			key: AMAP_KEY, // 请使用自己的高德地图API Key
			version: '2.0',
			plugins: ['AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Marker', 'AMap.Geocoder']
		})
			.then((AMap) => {
				// 如果没有传入地址，则使用默认地址
				const resolvedAddress = address || '广州市花都区花都广场';

				// 创建Geocoder实例，用于地址解析
				const geocoder = new AMap.Geocoder({
					city: '020', // 设置城市为佛山
					radius: 500 // 搜索范围
				});

				// 使用Geocoder解析传入的地址
				geocoder.getLocation(resolvedAddress, (status, result) => {
					if (status === 'complete' && result.geocodes.length) {
						const { lng, lat } = result.geocodes[0].location;
						console.log(`地图中心点的地址为：` + address + `，经纬度 ${lng},${lat}`);

						// 初始化地图
						mapIns.value = new AMap.Map(mapRef.value, {
							zoom: 19,
							center: [lng, lat], // 地图中心点
							resizeEnable: true
						});

						// 添加地图标记
						mapMarker.value = new AMap.Marker({
							position: [lng, lat], // 标记位置
							map: mapIns.value
						});

						// 更新 formData 的经纬度
						form.value.latitude = lat;
						form.value.longitude = lng;

						// 使用逆地址编码获取详细地址
					} else {
						console.error('地址解析失败，使用默认地图中心');
						mapIns.value = new AMap.Map(mapRef.value, {
							zoom: 19,
							center: [113.122717, 23.028762], // 默认中心点
							resizeEnable: true
						});
					}

					// 点击地图更新标记和经纬度
					mapIns.value.on('click', (e) => {
						const { lng, lat } = e.lnglat;

						// 更新地图标记位置
						mapMarker.value.setPosition([lng, lat]);

						// 更新 formData 中的经纬度
						form.value.latitude = lat;
						form.value.longitude = lng;

						console.log(`用户点击了地图：经度 ${lng}, 纬度 ${lat}`);
					});
					// 地图加载完成事件
					mapIns.value.on('complete', () => {});
				});
			})
			.catch((e) => {
				console.error('地图加载失败', e);
			});
	};

	const confirmLoading = ref(false);
	const onConfirm = () => {
		const { lng, lat } = mapIns.value.getCenter();
		result.lngAndLat = `${lng}, ${lat}`;
		form.value.latitude = lat;
		form.value.longitude = lng;
		visible.value = false;
	};

	// 新增上传逻辑
	const beforeUploadTitleDeed = (file) => {
		const fileType = file.type;

		if (fileType !== 'application/pdf') {
			message.error('仅支持上传 PDF 文件');
			return false;  // 阻止非 PDF 文件上传
		}

		const formData = new FormData();
		formData.append('file', file);

		// 上传文件
		landlordApi.uploadTitleDeed(formData)
			.then((response) => {
				form.value.titleDeed = response.data[0].url;
				form.value.fileType = response.data[0].fileType;
				message.success('产权证明上传成功');
			})
			.catch((error) => {
				message.error('上传失败');
			});

		return false;  // 阻止默认上传行为
	};


	// 新增删除逻辑
	const handleRemoveTitleDeed = () => {
		form.value.titleDeed = '';
	};

	// 新增预览逻辑
	const previewTitleDeed = () => {
		window.open(form.value.titleDeed, '_blank'); // 打开预览页面
	};
</script>

<style scoped>
	.form-row {
		display: flex;
		gap: 24px;
		margin-bottom: 16px;
	}

	.form-col {
		flex: 1;
	}

	.ml-4 {
		margin-left: 0;
		color: #0056b3;
		font-weight: bold;
		border: 1px dashed #0056b3;
	}

	.map-container {
		height: 50vh;
	}

	/* 调整按钮间距 */
	.ant-upload-list {
		margin-bottom: 8px;
	}
</style>
